import {Detail} from "../classes/MyUI.js";
import MyComponent from "../classes/MyComponent.js";
import {generateElement, trans10to16} from "../functions/common.js";

const detail = new Detail(
    "存储器模拟",
    ["By Louis，2021-01-15", "第一个块级元素就是要加入的元素"],
    {margin: "30px 40px"}
);
document.getElementById("detail").appendChild(detail.getElement());


export class MyStorage extends MyComponent {
    constructor(size) {
        super();
        this.elem = generateElement({
            type: "div",
            height: "400px",
            width: "160px",
            border: "1px solid #c2c2c2",
            overflow: "hidden",
            backgroundColor: "#f2f2f2",
            margin: "5px 5px"
        });
        this.elem.innerHTML = "<div id=\"blockContainer\" style=\"margin: 5px 5px\"></div>\n";
        this.size = size ? size : 32;
        this.dataArray = [];
    }

    init(size) {
        this.size = size ? size : 32;
        this.blockContainer = document.getElementById("blockContainer");
        for (let i = 0; i < this.size; i++) {
            let tmp = generateElement({
                type: "div",
                margin: "5px 5px",
                backgroundColor: "#5FB878",
                height: "24px",
                lineHeight: "24px",
                border: "none",
                innerText: trans10to16(i),
                padding: "0 5px"
            });
            this.blockContainer.appendChild(tmp);
            this.dataArray[i] = {data: null, elem: tmp, isFree: true};
        }
    }

    writeData(address, content) {
        this.dataArray[address].data = content;
        this.dataArray[address].isFree = false;
        this.dataArray[address].elem.style.backgroundColor = "#FF5722";
    }

    readData(address) {
        return this.dataArray[address].data;
    }

    withdrawData(address) {
        this.dataArray[address].elem.style.backgroundColor = "#5FB878";
        this.dataArray[address].isFree = true;
    }

    getElementByAddress(address) {
        return this.dataArray[address].elem;
    }

    isBlank(address) {
        return this.dataArray[address].isFree;
    }

    animeMoveFind(address) {
        try {
            anime({
                targets: this.blockContainer,
                translateY: -29 * address,
                easing: 'easeInOutQuad',
                duration: 800
            });
        } catch (e) {
            console.log("Error:MyStorage.animeMoveFind", e)
        }
    }
}

let myStorage = new MyStorage();
document.getElementById("storage").appendChild(myStorage.getElement());
myStorage.init();

myStorage.writeData(3, "This is a block");

let visit = [1, 7, 2, 0, 45, 67, 12, 99, 56, 78, 23, 19];
let index = 1;
let visitLen = visit.length;
let timer = setInterval(() => {
    myStorage.animeMoveFind(visit[index%visitLen]%32);
    index = (index+1)%visitLen;
}, 1000);